<template>
  <div class="profile">
    <div class="profile-header">
      <el-page-header @back="goBack" content="个人中心"></el-page-header>
    </div>
    <el-card class="profile-card">
      <div slot="header" class="card-header">
        <span class="header-title">个人信息</span>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="userInfo" label-width="100px" size="medium" style="width: 50%; margin: 0 auto;">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled>
                <template slot="prepend">
                  <i class="el-icon-user"></i>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email" disabled>
                <template slot="prepend">
                  <i class="el-icon-message"></i>
                </template>
                <template slot="append">
                  <el-button v-if="!userInfo.email" type="primary" @click="startEmailVerification">绑定邮箱</el-button>
                  <el-button v-else type="primary" @click="startEmailVerification">修改邮箱</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="isEditingEmail" label="验证码">
              <el-input v-model="verificationCode" placeholder="请输入验证码">
                <template slot="prepend">
                  <i class="el-icon-key"></i>
                </template>
                <template slot="append">
                  <el-button type="success" @click="sendVerificationCode" :disabled="countdown > 0">
                    {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="isEditingEmail" label="新邮箱">
              <el-input v-model="newEmail" placeholder="请输入新邮箱">
                <template slot="prepend">
                  <i class="el-icon-message"></i>
                </template>
                <template slot="append">
                  <el-button type="primary" @click="verifyEmail()">提交</el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <div class="button-group">
                <el-button type="primary" @click="showChangePasswordDialog" icon="el-icon-lock">修改密码</el-button>
                <el-button @click="goBack" icon="el-icon-back">返回首页</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="我的订单" name="orders">
          <el-table :data="orderList" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="订单号" width="180"></el-table-column>
            <el-table-column prop="good_title" label="商品名称"></el-table-column>
            <el-table-column label="商品图片">
              <template slot-scope="scope">
                <img :src="scope.row.good_img" style="width: 50px;height: 50px;">
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="120"></el-table-column>
            <el-table-column prop="price" label="价格" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="创建时间" width="180"></el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="30%" center>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password">
            <template slot="prepend">
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password">
            <template slot="prepend">
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password">
            <template slot="prepend">
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePassword()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sendBindEmail, sendChangeEmail } from '@/api/email'
import { modify_pwd, bindEmailConfirm, changeEmailConfirm } from '@/api/user_api'
import { get_user_orders } from '@/api/order_api'
import { AES_Encrypt } from '@/util/aes'

export default {
  name: 'Profile',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      activeTab: 'basic',
      userInfo: JSON.parse(localStorage.getItem('user')) || {},
      isEditingEmail: false,
      newEmail: '',
      verificationCode: '',
      countdown: 0,
      countdownTimer: null,
      passwordDialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      // 订单相关数据
      orderList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.getOrders()
  },
  methods: {
    goBack () {
      this.$router.push('/')
    },
    startEmailVerification () {
      this.isEditingEmail = true
      this.newEmail = ''
      this.verificationCode = ''
      this.countdown = 0
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
      }
    },
    async sendVerificationCode () {
      try {
        // 校验邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

        let res = {}
        if (this.userInfo.email) {
          if (!emailRegex.test(this.userInfo.email)) {
            this.$message.error('请输入正确的邮箱格式')
            return
          }
          res = await sendChangeEmail(this.userInfo.email)
        } else {
          if (!this.newEmail) {
            this.$message.warning('请输入新邮箱')
            return
          }

            
          res = await sendBindEmail(this.newEmail)
        }

        if (res.data.code === 200) {
          this.$message.success('验证码已发送到您的邮箱')
          this.countdown = 60
          this.countdownTimer = setInterval(() => {
            this.countdown--
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer)
            }
          }, 1000)
        } else {
          this.$message.error(res.data.message)
        }
      } catch (error) {
        this.$message.error('发送验证码失败')
      }
    },
    async verifyEmail () {
      if (!this.newEmail) {
        this.$message.warning('请输入新邮箱')
        return
      }
      if (!this.verificationCode) {
        this.$message.warning('请输入验证码')
        return
      }
      try {
        const res = this.userInfo.email ?
          await changeEmailConfirm(this.userInfo.user_id, this.newEmail, this.verificationCode) :
          await bindEmailConfirm(this.userInfo.user_id, this.newEmail, this.verificationCode)
        if (res.data.code === 200) {
          this.$message.success('邮箱绑定成功')
          this.isEditingEmail = false
          // 更新本地存储的用户信息
          const user = JSON.parse(localStorage.getItem('user'))
          user.email = this.newEmail
          localStorage.setItem('user', JSON.stringify(user))
          this.userInfo.email = this.newEmail
          this.newEmail = ''
          this.verificationCode = ''
          if (this.countdownTimer) {
            clearInterval(this.countdownTimer)
          }
        } else {
          this.$message.error(res.data.message)
        }
      } catch (error) {
        this.$message.error(error.response.data.message)
      }
    },
    showChangePasswordDialog () {
      this.passwordDialogVisible = true
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    },
    async changePassword () {
      console.log(this.passwordForm)
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await modify_pwd({
              id: this.userInfo.user_id,
              pwd: AES_Encrypt(this.passwordForm.oldPassword),
              nPwd: AES_Encrypt(this.passwordForm.newPassword)
            })
            if (res.data.code === 200) {
              this.$message.success('密码修改成功')
              this.passwordDialogVisible = false
            } else {
              this.$message.error(res.data.message)
            }
          } catch (error) {
            this.$message.error('密码修改失败')
          }
        }
      })
    },
    async getOrders() {
      this.loading = true
      try {
        const res = await get_user_orders({
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userInfo.user_id
        })
        if (res.data.code === 200) {
          this.orderList = res.data.data.list
          this.total = res.data.data.total
        }
      } catch (error) {
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getOrders()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getOrders()
    },
    getStatusType(status) {
      const statusMap = {
        0: 'info',    // 待支付
        1: 'success', // 已支付
        2: 'warning', // 已发货
        3: 'success', // 已完成
        4: 'danger'   // 已取消
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    }
  }
}
</script>

<style scoped>
.profile {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-card {
  max-width: 80%;
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.el-input-group__prepend {
  background-color: #f5f7fa;
}

.el-form-item {
  margin-bottom: 25px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>